//
//  FloatADManager.swift
//  iPhone
//
//  Created by Toj on 6/13/22.
//

import UIKit

/**
 1. 轮播, 带小点点
 2. 定时器
 3. 关闭逻辑
 4. 展示逻辑, 图片加载回来后展示(待定)
 */

open class FloatADManager: NSObject {
    
    static let manager = FloatADManager()
    
    var floatADs: [FloatADModel]?
    var pageADs: [String: [FloatADModel]]?
    var vcPitADs: [String: [String: [FloatADModel]]]?
    
    public func requestFloatADS() {
        if let json = UserDefaults.standard.string(forKey: "STFloatADCacheKey") {
            deserialize(json: json, model: [FloatADModel].self) { response in
                
                guard let data = response.data else { return }
                
                self.floatADCallBack(data: data)
            }
        }
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.deserialize(model: [FloatADModel].self) { response in
                guard let data = response.data else { return }
                
                let json = response.toJSONString()
                UserDefaults.standard.set(json, forKey: "STFloatADCacheKey")
                self.floatADCallBack(data: data)
            }
        }
    }
    
    private var cuttrentCirculationViews: NSPointerArray?
    public func setCuttrentViews(_ views: [STCirculationView]?) {
        
        let count = cuttrentCirculationViews?.count ?? 0
        for i in 0..<count {
            guard let pointer = cuttrentCirculationViews?.pointer(at: i) else { continue }
            let view = Unmanaged<STCirculationView>.fromOpaque(pointer).takeUnretainedValue()
            view.removeFromSuperview()
        }
        
        let pointerArray = NSPointerArray.weakObjects()
        views?.forEach({
            let pointer = Unmanaged.passUnretained($0).toOpaque()
            pointerArray.addPointer(pointer)
        })
        cuttrentCirculationViews = pointerArray
    }
    
    public func fetchVCADs(page name: String, completion:((_ ads: [String: [FloatADModel]]?)->Void)?) {
        guard name.count > 0 else {
            completion?(nil)
            return
        }
        //print("-->toj: show: \(name)")
        guard let ads = pageADs?[name], ads.count > 0 else {
            completion?(nil)
            return
        }
        //print("-->toj: show: " + name + ", count: \(ads.count)")
        if let vcADs = vcPitADs?[name], vcADs.count > 0 {
            // 如果已经处理过的直接返回
            completion?(vcADs)
            return
        }
        // 当前没有处理过vc内部的广告
        var vcADs = [String: [FloatADModel]]()
        
        for ad in ads {
            guard !ad.isClosed else { continue }
            // print("-->toj: show name: " + name + ", space_id: \(ad.space_id)")
            // 坑的key
            let pitKey = ad.pitKey
            // 取出当前ad对应的坑数据
            var pitADs = vcADs[pitKey]
            // 空坑实例化一个坑
            if pitADs == nil {
                pitADs = [FloatADModel]()
            }
            // 往坑里填充数据
            pitADs?.append(ad)
            vcADs[pitKey] = pitADs
        }
        vcPitADs?[name] = vcADs
        completion?(vcADs)
    }
    
    public func adGroup(floatADs: [FloatADModel]) {
        self.floatADs = floatADs
        var pADs = [String: [FloatADModel]]()
        
        for floatAD in floatADs {
            guard let pages = floatAD.page_code else {  continue }
            
            for page in pages {
                guard let pName = page.cm_trim.cm_split("?").first,
                      pName.count > 0 else { continue }
                var ads = pADs[pName]
                if ads == nil {
                    ads = [FloatADModel]()
                }
                ads?.append(floatAD)
                pADs[pName] = ads
            }
        }
        
        pageADs = pADs
        
        //for (pagead, ads) in pADs {
            // print("-->toj: " + pagead + ", count: \(ads.count)")
        //}
    }
    
    private func floatADCallBack(data: [FloatADModel]) {
        
        let queue = DispatchQueue.global(qos: .default)
        queue.async {
            FloatADManager.manager.adGroup(floatADs: data)
            
            DispatchQueue.main.async {
                let vc = UIViewController.vc_topViewController as? STBaseViewController
                
                guard let path = vc?.pagePath, path.count > 0 else { return }
                FloatADManager.manager.fetchVCADs(page: path) { ads in
                    vc?.ads = ads
                }
            }
        }
    }
    
    private func deserialize<T: STJSONCodable>(model:T.Type, completion: ((_ t:STResponse<T>)->())?) {
        let json = floatADJson.to_json
        
        deserialize(json: json, model: model, completion: completion)
    }
    
    private func deserialize<T: STJSONCodable>(json: String?, model:T.Type, completion: ((_ t:STResponse<T>)->())?) {
        
        if let rModel = STResponse<T>.deserialize(from: json) {
            completion?(rModel)
            return
        }
        
        let rModel = STResponse<T>()
        rModel.message = "数据异常, 请联系官方人员"
        completion?(rModel)
    }
}
